/*
 * @Descripttion: 
 * @Author: hejiajun
 * @Date: 2021-09-14 15:30:40
 * @LastEditors: hejiajun
 * @LastEditTime: 2021-09-27 15:08:11
 */
import { message } from 'ant-design-vue';
import axios from 'axios';
import untils from '@/untils/common';
const { NODE_ENV } = process.env;

class HttpRequest {
  constructor() {
    this.baseUrl = '';
    this.queue = {};
  }
  getInsideConfig() {
    const config = {
      baseURL: this.baseUrl,
      headers: {},
    };
    return config;
  }
  distroy(url) {
    delete this.queue[url];
    if (!Object.keys(this.queue).length) {
      // Spin.hide()
    }
  }
  interceptors(instance, url, des) {
    // 请求拦截
    instance.interceptors.request.use(
      config => {
        // 添加全局的loading...
        if (!Object.keys(this.queue).length) {
          // Spin.show() // 不建议开启，因为界面不友好
        }
        this.queue[url] = true;
        return config;
      },
      error => {
        return Promise.reject(error);
      }
    );
    // 响应拦截
    instance.interceptors.response.use(
      res => {
        this.distroy(url);
        const { data } = res;

        // return { data, status }

        if (data.code == 200 || (typeof data.code === 'undefined' && data)) {
          // 验证数据权限
          let { data: params } = res.config;

          if (NODE_ENV !== 'dev' && NODE_ENV !== 'sit') {
            // 只有登陆过或者dev/sit环境才不需要验证登录
            if (params && data.data && data.data.data && data.data.data.length) {
              let { serviceId } = JSON.parse(params);
              data.data.data = untils.$verifyDataPermissions(data.data.data, serviceId, des); // 根据serviceId和过滤数据权限
            }
          }

          return data;
        } else {
          if (data.message) {
            message.error(data.message);
          } else {
            if (typeof data.data == 'string') {
              message.error(data.data);
            } else {
              console.error('接口报错');
            }
          }
          return data;
        }
      },
      error => {
        this.distroy(url);
        return Promise.reject(error);
      }
    );
  }
  request(options, des) {
    const instance = axios.create();
    options = Object.assign(this.getInsideConfig(), options);
    this.interceptors(instance, options.url, des);
    return instance(options);
  }
}
export default HttpRequest;
